package com.ffspace.web;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ff.blog.common.BaseResult;
import com.ff.blog.enums.ErrorCode;
import com.ffspace.blog.core.dal.dataobject.Blog;
import com.ffspace.blog.core.dal.dataobject.User;
import com.ffspace.blog.service.BlogService;

@Controller
public class BlogController {
	private static Logger logger = LoggerFactory
			.getLogger(BlogController.class);
	
	@Autowired
	private BlogService blogService;
	
	@ResponseBody
	@RequestMapping("/createBlog.htm")
	public BaseResult<Blog> createBlog(HttpServletRequest request, String title, String content) throws Exception
	{
		BaseResult<Blog> result = new BaseResult<Blog>();
		try
		{
			HttpSession session = request.getSession();
			if (session == null || null == session.getAttribute("user"))
			{
				logger.error("createBlog error:no login");
				result.setCode(ErrorCode.NOT_LOGIN);
				result.setSuccess(false);
				result.setMessage("没有登录");
				return result;
			}
			
			User user = (User)session.getAttribute("user");
			
			Blog blog = new Blog();
			blog.setUserId(user.getId());
			blog.setContent(content);
			blog.setTitle(title);
			result = blogService.createBlog(blog);
		}
		catch (Exception e)
		{
			logger.error("createBlog error", e);
			result.setSuccess(false);
			result.setMessage("服务器错误");
		}
		
		return result;
	}
	
	@ResponseBody
	@RequestMapping("/queryBlog.htm")
	public BaseResult<List<Blog>> queryBlog(HttpServletRequest request, Integer pageNum, Integer currentPage, boolean searchSelf) throws Exception
	{
		BaseResult<List<Blog>> result = new BaseResult<List<Blog>>();
		try
		{
			Map<String, Object> condition = new HashMap<String, Object>();
			if (searchSelf)
			{
				HttpSession session = request.getSession();
				if (session != null && null != session.getAttribute("user"))
				{
					User user = (User)session.getAttribute("user");
					condition.put("userId", user.getId());
				}
				else
				{
					result.setSuccess(true);
					return result;
				}
			}
			int offset = (currentPage - 1) * pageNum;
			if (offset < 0)
			{
				offset = 0;
			}
			condition.put("limit", pageNum);
			condition.put("offset", offset);
			result = blogService.queryPage(condition);
			return result;
		}
		catch (Exception e)
		{
			logger.error("queryBlog error", e);
			result.setSuccess(false);
			result.setMessage("服务器错误");
		}
		
		return result;
	}
}
